package org.xlp.db.bridge.defination;

import org.xlp.db.tableoption.annotation.XLPEntity;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;

/**
 * Description: 函数返回值工具类
 * <br/>date: 2024/4/26 22:54
 *
 * @version 1.0
 * @author: xlp
 */
public class ReturnTypeUtils {
    /**
     * 通过函数的返回类型，获取需要查询出数据的返回bean类型
     * @param methodReturnType
     * @return 假如未找到实体类型，字节返回null，否则返回实体类型
     */
    public Class<?> getBeanClassByReturnType(Type methodReturnType){
        // 函数返回类型为void，直接返回null
        if (methodReturnType == null || methodReturnType == Void.TYPE || methodReturnType == Void.class){
            return null;
        }

        if (methodReturnType instanceof Class){
            Class<?> returnType = (Class<?>) methodReturnType;
            // 返回实体类型
            return getBeanClassByReturnType(returnType);
        } else if (methodReturnType instanceof ParameterizedType){
            ParameterizedType type = (ParameterizedType) methodReturnType;
            Type actualTypeArgument = type.getActualTypeArguments()[0];
            if (Collection.class.isAssignableFrom((Class<?>) type.getRawType())
                    && actualTypeArgument instanceof Class){
                return getBeanClassByReturnType(((Class<?>) actualTypeArgument));
            }
        }

        return null;
    }

    private Class<?> getBeanClassByReturnType(Class<?> checkClass){
        return checkClass.getAnnotation(XLPEntity.class) != null ? checkClass : null;
    }
}
